package com.example.ddmaps;

import java.util.ArrayList;
import java.util.List;

import model.Usuario;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.ddmaps.R;
import com.ddmaps.util.AddItemizedOverlay;
import com.ddmaps.util.GPSTracker;
import com.ddmaps.util.JSONParser;
import com.ddmaps.util.LocalCache;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

public class MapaFragment extends Fragment implements LocationListener{

		
	private MapView mapView;
	private FrameLayout frame;
	private MapController mc;
	private AddItemizedOverlay itemizedOverlay;
	private GeoPoint geoPointAtual;
	private double latitude;
	private double longitude;
	private OverlayItem overlayitem;
	private List<Overlay> mapOverlays;
	private GPSTracker gps;
	private LocationManager locationManager;
	private String provider;
	 private Projection projection;
	 private GeoPoint ggeoPointOld;
	private Drawable motoristaIMG;
	private Drawable usuarioIMG;
	private ArrayList<Usuario> listaUsuarios;
	private JSONParser jsonParser = new JSONParser();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		listaUsuarios = LocalCache.getInstance().getListaUsuarios();
		motoristaIMG = this.getResources().getDrawable(R.drawable.mark_red);
		usuarioIMG = this.getResources().getDrawable(R.drawable.mark_blue);
		
		//locMgr = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
		//locLstnr = new DDLocationListener();
		//locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);
	}
	
	 @Override
	public void onResume() {
	    super.onResume();
	    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,300 , 200 , this);
	  }
	 
	 
	 @Override
	 public void onDestroy() {
		super.onDestroy(); 
		//locationManager.
	 }
		 
	 

	@Override
	  public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                            Bundle savedInstanceState) {
		if (frame == null) {
		 frame = new FrameLayout(getActivity());
		}
		frame.removeAllViews();
	    return frame;
	  }

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, false);
		Location location = locationManager.getLastKnownLocation(provider);

		if (mapView == null) {
			// public MapView mapView = null; // Public defined Variable
			mapView = new MapView(getActivity(), "0tCSXiEW_eai0Ex_4a37YSjBQLdmykEkAQdD4gw");
		}
		
		mapView.setBuiltInZoomControls(true);
		mapView.setClickable(true);
		
		mc = mapView.getController();

		mapOverlays = mapView.getOverlays();

		Double userLatitude = LocalCache.getInstance().getUserLatitude();
		Double userLongitude = LocalCache.getInstance().getUserLongitude();
		latitude = userLatitude;
		longitude = userLongitude;
		
		geoPointAtual = new GeoPoint((int) (userLatitude * 1E6),
				(int) (userLongitude * 1E6));
		
		addMotorista();
		
		new GravaCoordenada().execute();
		
		mc.animateTo(geoPointAtual); 
		mc.setZoom(15);
		((ViewGroup) getView()).addView(mapView);
	}
	
	
	
	public void addMotorista() {
		
		mapOverlays.clear();
		
		itemizedOverlay = new AddItemizedOverlay(motoristaIMG, getActivity());
		
		overlayitem = new OverlayItem(geoPointAtual, "Motorista", "");
		
		itemizedOverlay.addOverlay(overlayitem);
		
		mapOverlays.add(itemizedOverlay);
		
		itemizedOverlay.populateNow();

		for (Usuario u : listaUsuarios) {
			
			Double userLatitude = Double.parseDouble(u.getLatitude());
			Double userLongitude = Double.parseDouble(u.getLongitude());
			
			GeoPoint userGeoPoint = new GeoPoint((int) (userLatitude * 1E6),
					(int) (userLongitude * 1E6));
			

			itemizedOverlay = new AddItemizedOverlay(usuarioIMG, getActivity());
			
			overlayitem = new OverlayItem(userGeoPoint, " " + u.getNome() , " " + u.getEndereco());
			
			itemizedOverlay.addOverlay(overlayitem);
			
			mapOverlays.add(itemizedOverlay);
			
			itemizedOverlay.populateNow();
			
			new GravaCoordenada().execute();

		}
		
	}
	

	@Override
	public void onLocationChanged(Location location) {
		Double lat = location.getLatitude();
	    Double lng = location.getLongitude();
	    
	    latitude = lat;
	    longitude = lng;
	   	 
	    geoPointAtual = new GeoPoint((int) (lat * 1E6),
				(int) (lng * 1E6));
	 
	    
	    addMotorista();
	    
	    
	 mc.animateTo(geoPointAtual);
	 mc.setZoom(17);
	    mapView.invalidate();
	    ggeoPointOld = geoPointAtual;
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	  
	class MyOverlay extends Overlay{


		private GeoPoint gP1;
		private GeoPoint gP2;

		public MyOverlay(GeoPoint gp1, GeoPoint gp2){
			this.gP1 = gp1;
			this.gP2 = gp2;

	    }   

	    public void draw(Canvas canvas, MapView mapv, boolean shadow){
	        super.draw(canvas, mapv, shadow);

	        Paint   mPaint = new Paint();
	        mPaint.setDither(true);
	        mPaint.setColor(Color.RED);
	        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
	        mPaint.setStrokeJoin(Paint.Join.ROUND);
	        mPaint.setStrokeCap(Paint.Cap.ROUND);
	        mPaint.setStrokeWidth(2);

	       // GeoPoint gP1 = new GeoPoint(19240000,-99120000);
	      //  GeoPoint gP2 = new GeoPoint(37423157, -122085008);

	        Point p1 = new Point();
	        Point p2 = new Point();
	        Path path = new Path();

	        projection.toPixels(gP1, p1);
	        projection.toPixels(gP2, p2);

	        path.moveTo(p2.x, p2.y);
	        path.lineTo(p1.x,p1.y);

	        canvas.drawPath(path, mPaint);
	    }
	  
	}
	
	
	
	
	
	
	
public class GravaCoordenada extends AsyncTask<GeoPoint, Void, String> {
		
	

		@Override
		protected String doInBackground(GeoPoint... args) {

		/*	List<NameValuePair> params = new ArrayList<NameValuePair>();
			
			//LocalCache.getInstance().getTrajeto()

			params.add(new BasicNameValuePair("oid_trajeto", "1"));
			params.add(new BasicNameValuePair("oid_viagem", "1"));
			params.add(new BasicNameValuePair("latitude", String.valueOf(geoPointAtual.getLatitudeE6())));
			params.add(new BasicNameValuePair("longitude", String.valueOf(geoPointAtual.getLongitudeE6())));*/
			
			try {
			JSONObject json = new JSONObject();
			json.put("oid_trajeto", "1");
			json.put("oid_viagem", "1");
			json.put("latitude", String.valueOf(latitude));
			json.put("longitude", String.valueOf(longitude));
			
			
				String result = jsonParser.makePost("http://ddmapsjpa.appspot.com/coordenada/gravar", json);
				Log.e("JSON GRAVAR", result);
			} catch (Exception e) {
				
				Log.e("JSON GRAVAR", e.getMessage());
				// TODO: handle exception
			}
			
			

			//String result = jsonParser.makeHttpRequest("http://ddmapsjpa.appspot.com/coordenada/gravar", "POST",
				//	params);
			
			
			

/*
			try {
				trajetos = new JSONArray(json);

				if (trajetos != null) {
					for (int i = 0; i < trajetos.length(); i++) {
						JSONObject c = trajetos.getJSONObject(i);

						listaTrajetos.add(c.getString(OID_TRAJETO));
					}
				} else {
					Log.d("Albums: ", "null");
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}*/

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			
	


		}

	}
	  
	
	  

}
